document.addEventListener('DOMContentLoaded', function () {
    // 从 sessionStorage 获取用户信息
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');

    document.querySelector('.work-id').textContent = `工号：${userInfo.uid || '未知'}`;
    document.querySelector('.username').textContent = `姓名：${userInfo.uname || '未知'}`;

    const userRole = userInfo.urole === 1 ? 'admin' : 'user';
    const haveFace = userInfo.have_face || 0;

    initMenu();

    function initMenu() {
        if (userRole !== 'admin') {
            document.querySelectorAll('[data-role="admin"]').forEach(item => {
                item.style.display = 'none';
            });
        }

        const menuItems = document.querySelectorAll('.menu-item');

        if (haveFace === 0) {
            // 没有录入人脸，强制显示人脸录入页面
            initCamera();
            showPage('face-register');

            document.querySelectorAll('.menu-item').forEach(item => {
                if (item.dataset.page !== 'face-register') {
                    item.style.display = 'none';
                }
            });

        } else {
            showPage('home');
            document.querySelectorAll('[data-page="face-register"]').forEach(item => {
                item.style.display = 'none';
            });

            // 菜单点击事件
            menuItems.forEach(item => {
                item.addEventListener('click', function () {
                    const submenu = this.querySelector('.submenu');
                    if (submenu) {
                        submenu.style.display = submenu.style.display === 'block' ? 'none' : 'block';
                    } else {
                        showPage(this.dataset.page);
                    }
                });
            });

            // 菜单点击事件
            document.querySelectorAll('.submenu-item').forEach(item => {
                item.addEventListener('click', function (e) {
                    e.stopPropagation();
                    showPage(this.dataset.page);
                });
            });
        }
    }

    function showPage(pageId) {
        document.querySelectorAll('.page').forEach(page => {
            page.style.display = 'none';
        });

        const selectedPage = document.getElementById(pageId);
        if (selectedPage) {
            selectedPage.style.display = 'block';
        }
    }

    function initCamera() {
        const video = document.getElementById('faceVideo');
        const captureBtn = document.getElementById('captureBtn');

        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({ video: true })
                .then(function (stream) {
                    video.srcObject = stream;
                })
                .catch(function (error) {
                    console.error("摄像头访问失败:", error);
                });
        }

        captureBtn.addEventListener('click', function () {
            const canvas = document.createElement('canvas');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            canvas.getContext('2d').drawImage(video, 0, 0);

            // 获取图片的 base64 数据
            const imageData = canvas.toDataURL('image/jpeg');
            const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');

            console.log(JSON.stringify({
                userinfo: userInfo,
                img: imageData
            }));
            fetch('http://localhost:8888/face/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userinfo: userInfo,
                    img: imageData
                })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.result) {
                        alert('人脸录入成功！');
                        // 更新本地存储的用户信息中的 have_face 状态
                        userInfo.have_face = 1;
                        sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
                        const stream = video.srcObject;
                        const tracks = stream.getTracks();
                        tracks.forEach(track => track.stop());
                        window.location.reload();
                    } else {
                        alert('人脸录入失败：' + (data.info || '未知错误'));
                    }
                })
                .catch(error => {
                    console.log('人脸录入错误:', error.message || error);
                    alert('人脸录入出错，请稍后重试!');
                });
        });
    }

    // 添加会议表单提交处理
    const meetingForm = document.getElementById('meetingForm');
    meetingForm.addEventListener('submit', function (e) {
        e.preventDefault();

        const meetingData = {
            topic: document.getElementById('topic').value,
            startTime: document.getElementById('startTime').value,
            endTime: document.getElementById('endTime').value,
            participants: selectedParticipants
        };
        console.log(JSON.stringify(meetingData));
        fetch('http://localhost:8888/meeting/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(meetingData)
        })
            .then(response => response.json())
            .then(data => {
                if (data.result) {
                    alert('会议创建成功！');
                    meetingForm.reset();
                    selectedParticipants = [];
                    document.getElementById('selectParticipants').textContent = '选择参会人员';
                } else {
                    alert('会议创建失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('创建会议错误:', error);
                alert('创建会议出错，请稍后重试!');
            });
    });

    // 参会人员选择
    const selectParticipantsBtn = document.getElementById('selectParticipants');
    const participantsModal = document.getElementById('participantsModal');
    const confirmParticipantsBtn = document.getElementById('confirmParticipants');
    const cancelParticipantsBtn = document.getElementById('cancelParticipants');

    // 添加获取用户列表的函数
    async function fetchUserList() {
        try {
            const response = await fetch('http://localhost:8888/user/');
            const data = await response.json();
            if (data.result) {
                return data.users.map(user => ({
                    workId: user.uid,
                    name: user.uname
                }));
            } else {
                console.error('获取用户列表失败:', data.error);
                return [];
            }
        } catch (error) {
            console.error('获取用户列表错误:', error);
            return [];
        }
    }

    // 选中的参会人员
    let selectedParticipants = [];

    // 修改选择参会人员按钮的点击事件
    selectParticipantsBtn.addEventListener('click', async function () {
        const participantsList = document.getElementById('participantsList');
        const users = await fetchUserList();

        participantsList.innerHTML = `
            <table class="participants-table">
                <thead>
                    <tr>
                        <th>选择</th>
                        <th>工号</th>
                        <th>姓名</th>
                    </tr>
                </thead>
                <tbody>
                    ${users.map(person => `
                        <tr>
                            <td>
                                <input type="checkbox" 
                                       value="${person.workId}"
                                       ${selectedParticipants.includes(person.workId.toString()) ? 'checked' : ''}>
                            </td>
                            <td>${person.workId}</td>
                            <td>${person.name}</td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        `;
        participantsModal.style.display = 'block';
    });

    // 修改确认按钮的点击事件
    confirmParticipantsBtn.addEventListener('click', function () {
        const checkboxes = document.querySelectorAll('.participants-table input[type="checkbox"]');
        selectedParticipants = Array.from(checkboxes)
            .filter(cb => cb.checked)
            .map(cb => cb.value);

        // 更新会议表单中的显示
        const participantsCount = selectedParticipants.length;
        const selectParticipantsBtn = document.getElementById('selectParticipants');
        selectParticipantsBtn.textContent = `已选择 ${participantsCount} 人`;

        participantsModal.style.display = 'none';
    });

    cancelParticipantsBtn.addEventListener('click', function () {
        participantsModal.style.display = 'none';
    });


    // 初始化用户会议列表
    async function initUserMeetings() {
        const tbody = document.querySelector('#userMeetingTable tbody');
        tbody.innerHTML = '';

        const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');

        try {
            const response = await fetch(`http://localhost:8888/meeting/${userInfo.uid}`);
            const data = await response.json();

            if (data.result) {
                data.meetings.forEach(meeting => {
                    const now = new Date();
                    const startTime = new Date(new Date(meeting.start_time).getTime() - 8 * 60 * 60 * 1000);
                    const endTime = new Date(new Date(meeting.end_time).getTime() - 8 * 60 * 60 * 1000);
                    const canCheckIn = now >= startTime && now <= endTime && !meeting.check_in_status;

                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${meeting.topic}</td>
                        <td>${meeting.start_time}</td>
                        <td>${meeting.end_time}</td>
                        <td>${meeting.check_in_status ? '已签到' : '未签到'}</td>
                        <td>
                            ${canCheckIn ?
                            `<button onclick="goToCheckIn(${meeting.mid}, '${meeting.topic}', '${meeting.start_time}', '${meeting.end_time}')" class="check-in-btn">签到</button>` :
                            '-'
                        }
                        </td>
                    `;
                    tbody.appendChild(tr);
                });
            } else {
                alert('获取会议列表失败：' + data.message);
            }
        } catch (error) {
            console.error('获取会议列表错误:', error);
            alert('获取会议列表出错，请稍后重试!');
        }
    }

 
    window.goToCheckIn = function (meetingId, topic, startTime, endTime) {
        showPage('check-in');
        // 保存会议信息到 sessionStorage
        sessionStorage.setItem('currentMeeting', JSON.stringify({
            id: meetingId,
            topic: topic,
            startTime: startTime,
            endTime: endTime
        }));

        document.getElementById('meeting-title').textContent = `会议主题：${topic}`;
        document.getElementById('meeting-time').textContent = `会议时间：${startTime} - ${endTime}`;
        initCheckInCamera(meetingId);
    }

    // 初始化签到摄像头
    function initCheckInCamera(meetingId) {
        const video = document.getElementById('checkInVideo');
        const captureBtn = document.getElementById('checkInCaptureBtn');

        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({ video: true })
                .then(function (stream) {
                    video.srcObject = stream;
                })
                .catch(function (error) {
                    console.error("摄像头访问失败:", error);
                });
        }

        captureBtn.addEventListener('click', async function () {
            const canvas = document.createElement('canvas');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            canvas.getContext('2d').drawImage(video, 0, 0);

            const imageData = canvas.toDataURL('image/jpeg').split(',')[1];
            const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');

            try {
                const faceResponse = await fetch('http://localhost:8888/face/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        img: imageData
                    })
                });
                const faceResult = await faceResponse.json();

                const checkInResponse = await fetch('http://localhost:8888/meeting/checkin', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        meetingId: meetingId,
                        userId: userInfo.uid,
                        faceResult: faceResult
                    })
                });
                const checkInResult = await checkInResponse.json();
                console.log(checkInResult.info);
                if (checkInResult.result) {
                    alert(`签到成功！\n工号：${userInfo.uid}\n姓名：${userInfo.uname}`);
                    const stream = video.srcObject;
                    const tracks = stream.getTracks();
                    tracks.forEach(track => track.stop());
                    showPage('user-meetings');
                    initUserMeetings();
                } else {
                    alert('签到失败：' + checkInResult.message);
                }
            } catch (error) {
                console.error('签到错误:', error);
                alert('签到出错，请稍后重试!');
            }
        });
    }

    initUserMeetings();

    // 初始化管理员会议查询列表
    async function initMeetingQuery() {
        const tbody = document.querySelector('#meetingTable tbody');
        tbody.innerHTML = '';

        try {
            const response = await fetch('http://localhost:8888/meeting/');
            const data = await response.json();

            if (data.result) {
                data.meetings.forEach(meeting => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${meeting.topic}</td>
                        <td>${meeting.start_time}</td>
                        <td>${meeting.end_time}</td>
                        <td>
                            <button onclick="showParticipantsDetails(${JSON.stringify(meeting).replace(/"/g, '&quot;')})" class="view-btn">
                                查看详情
                            </button>
                        </td>
                    `;
                    tbody.appendChild(tr);
                });
            } else {
                alert('获取会议列表失败：' + data.message);
            }
        } catch (error) {
            console.error('获取会议列表错误:', error);
            alert('获取会议列表出错，请稍后重试!');
        }
    }

    // 显示参会人员详情
    window.showParticipantsDetails = function (meeting) {
        const modal = document.getElementById('participantsModal');
        const participantsList = document.getElementById('participantsList');

        // 更新模态标题
        modal.querySelector('h3').textContent = `${meeting.topic} - 参会人员签到情况`;

        participantsList.innerHTML = `
            <table class="participants-table">
                <thead>
                    <tr>
                        <th>工号</th>
                        <th>姓名</th>
                        <th>签到状态</th>
                    </tr>
                </thead>
                <tbody>
                    ${meeting.participants.map(person => `
                        <tr>
                            <td>${person.uid}</td>
                            <td>${person.uname}</td>
                            <td>
                                <span class="status-badge ${person.check_in_status ? 'checked' : 'unchecked'}">
                                    ${person.check_in_status ? '已签到' : '未签到'}
                                </span>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        `;

        modal.style.display = 'block';
    }

    // 在 DOMContentLoaded 事件中添加初始化调用
    initMeetingQuery();

    // 清除当前会议信息
    sessionStorage.removeItem('currentMeeting');
}); 